package com.medvalley.tcm.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.medvalley.tcm.base.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class AliOSSService {

    @Value("${oss.access.key.id}")
    private String accessKeyId;
    @Value("${oss.access.secret}")
    private String accessKeySecret;
    @Value("${oss.endpoint}")
    private String endpoint;

    private static Logger LOGGER = LoggerFactory.getLogger(AliOSSService.class);

    public String upload(InputStream inputStream, String fileName, String bucketName) {
        try {
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();
            return "http://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (OSSException oe) {
            LOGGER.error(" upload error", oe);
            throw new BusinessException("上传错误");
        } catch (ClientException clientException) {
            LOGGER.error(" upload error", clientException);
            throw new BusinessException("上传错误");
        }
    }

}
